//
//  UserDefaults.swift
//  Mall-swift
//
//  Created by dfpo on 2020/10/15.
//  Copyright © 2020 Bob. All rights reserved.
//

import Foundation

@propertyWrapper
struct Default<T: Codable> {
    private struct Wrapper<T> : Codable where T : Codable {
        let wrapped : T
    }
    let key: String
    let defaultValue: T
    var wrappedValue: T {
        get {
            guard let data = UserDefaults.standard.object(forKey: key) as? Data
                else { return defaultValue }
            let value = try? PropertyListDecoder().decode(Wrapper<T>.self, from: data)
            return value?.wrapped ?? defaultValue
        }
        set {
            do {
                let data = try PropertyListEncoder().encode(Wrapper(wrapped:newValue))
                UserDefaults.standard.set(data, forKey: key)
            } catch {
                print(error)
            }
        }
    }
}

struct Defaults {
    
    /**
     例如在偏好里存储，用户是否注册
     
            取：Defaults.TSPlusServerTypeKey
            存：Defaults.TSPlusServerTypeKey = true
     */
    @Default(key: "TSPlusServerTypeKey", defaultValue: 0)
    static var TSPlusServerTypeKey: Int
}
